package com.yeziji.devops.config;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.yeziji.constant.SecuritySal;
import com.yeziji.utils.AesUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.nio.charset.StandardCharsets;

/**
 * devops 整体配置
 *
 * @author hwy
 * @since 2024/10/10 17:56
 **/
@Slf4j
@Configuration
@EnableConfigurationProperties(ConfigProperties.class)
@ConditionalOnProperty(name = "yzj.devops.enabled", matchIfMissing = true)
public class DevopsConfig {
    /**
     * 讀取配置
     */
    private final ConfigProperties configProperties;

    public DevopsConfig(ConfigProperties configProperties) {
        this.configProperties = configProperties;
    }

    /**
     * 刷新配置属性
     */
    @PostConstruct
    public void refreshConfigProperties() {
        if (this.configProperties == null) {
            return;
        }

        // 读配置文件
        String path = this.configProperties.getPath();
        if (StrUtil.isBlank(path)) {
            return;
        }

        // 读取配置文件之后解密获取真实的配置信息
        String propertiesContent = FileUtil.readString(path, StandardCharsets.UTF_8);
        String realPropertiesContent = AesUtils.decrypt(propertiesContent, SecuritySal.COMMON_SALT);
        // 覆盖配置
        BeanUtil.copyProperties(JSONUtil.toBean(realPropertiesContent, ConfigProperties.class, true), this.configProperties, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
    }
}